package es.usc.citius.servando.calendula.util.stock;

import org.jetbrains.annotations.NotNull;
import org.joda.time.LocalDate;

import java.util.ArrayList;
import java.util.List;

import es.usc.citius.servando.calendula.database.DB;
import es.usc.citius.servando.calendula.persistence.Medicine;
import es.usc.citius.servando.calendula.persistence.Schedule;
import es.usc.citius.servando.calendula.persistence.ScheduleItem;

public class MedicineScheduleStockProvider implements StockForDayProvider {
    private Medicine m;

    private List<Schedule> getSchedules() {
        return DB.schedules().findByMedicine(m);
    }

    public MedicineScheduleStockProvider(Medicine m) {
        this.m = m;
    }

    @Override
    public float stockNeededForDay(@NotNull LocalDate date) {
        float neededStock = 0F;
        List<Schedule> schedules = getSchedules();
        List<Schedule> filter = new ArrayList<>();
        for (Schedule schedule : schedules) {
            if (schedule.enabledForDate(date)) {
                filter.add(schedule);
            }
        }
        for (Schedule schedule : filter) {
            if (schedule.repeatsHourly()) {
                int intakes = schedule.hourlyItemsAt(date.toDateTimeAtStartOfDay()).size();
                neededStock += intakes * schedule.dose();
            } else {
                for (ScheduleItem item : schedule.items()) {
                    neededStock += item.getDose();
                }
            }
        }

        return neededStock;
    }
}
